<?php
/*** 
 *
 *
 *
 **/
require_once '../db/db.php';
require_once '../util/perm.php';
require_once '../util/msg.php';

function newThread( $fid, $title, $datum, $skey, $threadNum = true, $mode = 'post' ) {
  if( !hasPerm('thread.make') ) 
    return MSG_UNAUTHORIZED;

  $GLOBALS['__QNUM']++;
  try {
    $db = openDbConn();

    $title = $db->quote($title);
    $datum = $db->quote($datum);
    $mode = $db->quote($mode);
    $time = $db->quote(time());
    $uid = $db->quote($_SESSION['uid']);
    $smurfKey = $db->quote($smurfKey);

    $db->beginTransaction();
      $db->exec("INSERT INTO post (title, datum, smurfkey, stream,rank, indent, date, uid) VALUES ($title,$datum,$smurfKey, (SELECT MAX(stream) FROM post)+1, 1,0, $time, $uid);");
      $db->exec("INSERT INTO thread (fid, stream, prio, bumpdate, bumpuid) 
                        VALUES (${fid}, (SELECT MAX(stream) FROM post), 0, 0, 0);");
    if( $threadNum == false ) {
      $GLOBALS['__QNUM']++;
      // Another more transporatble query is "WHERE time=${time} AND datum=${datum} AND uid=${uid}"
      // Not sure if this will always return the correct value, but it should be pretty damn close.
      $post = $db->query('SELECT tid, rank FROM post WHERE post.id = '. $db->lastInsertId() .';' )->fetch(PDO::FETCH_ASSOC);
      $threadNum = $post['tid'];
      $postNum = $post['rank'];
      $post = NULL;
    }
    $db->commit();
  } catch ( PDOException $e ) {
    $db->rollback();
    print "ERROR: " . $e->getMessage() . "<br />";
    die();
  } 
};

function deleteThread( $forumNum, $threadNum ) {
  if( !hasPerm('delete.thread') ) 
    return -1;

  $GLOBALS['__QNUM']++;
  try {
    $db = openDbConn();
    $db->beginTransaction();
    $db->exec("DELETE FROM thread WHERE thread.fid = $forumNum AND thread.id = $threadNum");
    $db->exec("DELETE FROM post WHERE post.tid = $threadNum ");
    $db->commit();
  } catch ( PDOException $e ) {
    $db->rollback();
    print "ERROR: " . $e->getMessage() . "<br />";
    die();
  }
}
// XXX remove the crux of this
// int -> int -> string -> string -> bool
function setThread( $threadNum, $mode ) {
  if( !hasPerm('edit.thread') ) 
    return -1;

  $GLOBALS['__QNUM']++;
  try {
    $db = openDbConn();
    $mode = $db->quote( $mode );

    $db->beginTransaction();
    $db->exec("UPDATE thread SET mode = $mode WHERE id = $threadNum");
    $db->commit();
  } catch ( PDOException $e ) {
    $db->rollback();
    print "ERROR: " . $e->getMessage() . "<br />";
    die();
  }
}
function moveThread( $tid, $fid ) {
  return -1;
};
?>
